/*
 * Copyright 2010 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal.client.view;

import org.shalma.client.view.Adapter;
import org.shalma.client.view.AdapterRegistry;
import org.shalma.internal.reflection.Attribute;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Focusable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class AttributeView extends Composite implements ClickHandler {

	interface Binder extends UiBinder<Widget, AttributeView> {
	}

	private static Binder binder = GWT.create(Binder.class);

	private final Attribute attribute;
	private EntityView view;

	private Widget editor;
	private boolean edit;

	@UiField
	FlowPanel panel;

	@UiField
	Style style;

	public AttributeView(Attribute attribute, EntityView view) {

		this.attribute = attribute;
		this.view = view;

		initWidget(binder.createAndBindUi(this));

		Label label = new Label(attribute.getName());
		label.addStyleName(style.label());

		if (attribute.isReadOnly()) {
			label.addStyleName(style.label_readonly());
		} else {
			label.addClickHandler(this);
			label.addStyleName(style.label_editable());
		}

		panel.add(label);

		update();
	}

	@Override
	public void onClick(ClickEvent event) {
		edit = !edit;

		if (panel.getWidgetCount() > 1)
			panel.remove(1);
		update();
	}

	void update() {

		if (edit) {

			editor = null;
			final Adapter adapter = AdapterRegistry.instance.getView(attribute
					.getType());
			panel.add(adapter.edit(attribute.get(view.getObject())));
		}

		else {

			Object value = attribute.get(view.getObject());

			if (value != null) {
				final Adapter view = AdapterRegistry.instance.getView(attribute
						.getType());
				editor = view.read(value);
				// TODO
				if (editor instanceof Focusable) {
					((Focusable) editor).setFocus(true);
				}
				panel.add(editor);

			}

			// TODO null
		}
	}

	interface Style extends CssResource {

		String label();

		String label_readonly();

		String label_editable();
	}
}
